import React,{Component} from 'react';
class FilterableProductTable extends Component {
  constructor(props){
    super(props);
    this.state = {name:'',stocked:false};
    this.handleInputText = this.handleInputText.bind(this);
    this.handleInputCheckbox = this.handleInputCheckbox.bind(this);
  }
  handleInputText(name){
    this.setState({name:name})
  }
  handleInputCheckbox(stocked){
    this.setState({stocked:stocked})
  }
  render(){
    return(
      <div>
      <SearchBar handleInputText={this.handleInputText} handleInputCheckbox={this.handleInputCheckbox} />
      <ProductTable products={this.props.products} name={this.state.name} stocked={this.state.stocked}/>
      </div>
    );
  }
}

class SearchBar extends Component {
  constructor(props){
    super(props);
    this.handleChangeInputText = this.handleChangeInputText.bind(this);
    this.handleChangeInputChekbox = this.handleChangeInputChekbox.bind(this);
  }
  handleChangeInputText(e){
    this.props.handleInputText(e.target.value);
  }
  handleChangeInputChekbox(e){
    this.props.handleInputCheckbox(e.target.checked);
  }
  render(){
    return(
      <form>
      <input type="text" placeholder="Search" onChange={this.handleChangeInputText}/>
      <p>
        <label>
          <input type="checkbox" onChange={this.handleChangeInputChekbox}/>
          Only show products in stock.
        </label>
      </p>
      </form>
    );
  }
}

class ProductTable extends Component{
  render(){
    const rows = [];
    let lastCategory = null;
    this.props.products.forEach((product)=>{
      if(product.name.indexOf(this.props.name) === -1 || (!product.stocked && this.props.stocked)){
         return;
      }
      if(product.category !== lastCategory){
        rows.push(
          <ProductCategoryRow category={product.category} key={product.category}/>
        );
      }
      rows.push(
        <ProductRow product={product} key={product.name} />
      );
      lastCategory = product.category;
    });
    return(
      <table>
        <thead>
           <tr>
             <th>Name</th>
             <th>Price</th>
           </tr>
        </thead>
        <tbody>
            {rows}
        </tbody>
      </table>
    );
  }
}

class ProductCategoryRow extends Component{
  render(){
    return(
      <tr>
         <th colSpan="2">{this.props.category}</th>
      </tr>
    );
  }
}

class ProductRow extends Component{
  render(){
    const product = this.props.product;
    const name = product.stocked ? product.name : <span style={{color:'red'}}>product.name</span>;
    return(
      <tr>
        <td>{name}</td>
        <td>{product.price}</td>
      </tr>
    );
  }
}

export default FilterableProductTable;
